<template>
  <section id="mysql-manager-job">


      <el-form :inline="true" :model="filters" size="mini">
        <el-form-item>
          <el-input v-model="filters.sqlid" placeholder="请输入任务id"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"  @click="getSqlJobById">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="dialogFormVisible = true" >新增 DML/DDL</el-button>
        </el-form-item>
      </el-form>


    <!--新增任务-->
    <el-dialog title="新增任务" :visible.sync="dialogFormVisible" style="width: 100%" @open="openDialog">
      <el-form ref="addSqlJob" :model="addSqlJob"  size="mini" :rules="addsqlJobRules">
        <el-form-item label="数据库名" :label-width="formLabelWidth" style="width: 300px" prop="dbChoice">
          <el-select v-model="$route.params.name" placeholder="请选择数据库..." @focus="chooseDbs" disabled>
            <el-option v-for="db in this.addSqlJob.dbChoice " :label=db.name :value=db.name></el-option>
          </el-select>
        </el-form-item >

        <el-form-item label="类别" :label-width="formLabelWidth" style="width: 800px">
          <el-radio-group v-model="addSqlJob.type">
            <el-radio :label="1" >DML</el-radio>
            <el-radio :label="0" class="bg-red">DDL</el-radio>

          </el-radio-group>
        </el-form-item>
        <el-form-item label="SQL" :label-width="formLabelWidth" style="width: 800px">
          <el-radio-group v-model="contentType">
            <el-radio :label="0">在线编辑</el-radio>
            <el-radio :label="1">文件上传</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="DDL/DML" :label-width="formLabelWidth"  v-if="contentType === 0" prop="SqlEdit">
          <el-input v-model="addSqlJob.statement" autocomplete="off" type="textarea" :autosize="{ minRows: 4, maxRows: 10}" placeholder="请输入SQL"></el-input>
        </el-form-item>

        <el-form-item label="" :label-width="formLabelWidth"   prop="uploadSql" v-else>
          <el-col :span="10">
            <el-upload
                    class="upload-demo"
                    drag
                    :auto-upload="false"
                    action=""
                    accept=".sql"
                    :limit="1"
                    :show-file-list="true"

                    :on-change="fileChange"
                    :on-remove="fileChange"
                    :on-exceed="handleExceed"
                    :before-upload="beforeAvatarUpload"
                    :on-success="handleAvatarSuccess"
                    :on-error="handleAvatarError"
                    :file-list="sqlfileList"

            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">只能上传sql文件，且不超过<strong>2M</strong></div>
            </el-upload>
          </el-col>

        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input
                  placeholder="请输入备注"
                  v-model="addSqlJob.comment"
                  clearable>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="addSqlJobConfirm('addSqlJob')" size="small">确 定</el-button>
      </div>
    </el-dialog>

    <!--列表-->
    <el-table
            :data="sqlJobData.slice((currpage - 1) * pagesize, currpage * pagesize)"
            highlight-current-row
            style="width: 100%;"
            cell-style="padding:0"
            border>

      <el-table-column prop="id" label="id" width="80" sortable>

      </el-table-column>
      <el-table-column prop="createtime" label="提交时间" width="200" sortable>
      </el-table-column>
      <el-table-column prop="submitter" label="提交者" width="100" sortable>
      </el-table-column>
      <el-table-column prop="department" label="项目组" width="120"   sortable>
      </el-table-column>
      <el-table-column prop="dbname" label="数据库" width="120" sortable>
      </el-table-column>
      <el-table-column  label="类型" width="80" sortable>
        <template slot-scope="scope">
          <el-tag size="mini"  v-if="scope.row.type==='dml'">{{scope.row.type}}</el-tag>
          <el-tag size="mini" type="danger" v-else>{{scope.row.type}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column  label="SQL语句" >
        <template slot-scope="scope">
          <el-button type="text" style="color: black" >{{scope.row.statement}} ...</el-button>
          <el-button type="text"  icon="el-icon-download" style="float: right;color:lightseagreen" @click="downloadSqlJobFile(scope.row.id)">详情</el-button>
        </template>
      </el-table-column>
      <el-table-column  label="语法检查" width="150" >
        <template slot-scope="scope" >
          <div v-if="scope.row.syntaxCheck==='0'" >
            <i class="el-icon-question"  style="font-size:15px;color: dodgerblue;cursor: pointer" @click="sqlSyntaxCheck(scope.$index, scope.row)"></i>  待检测
          </div>
          <div v-else-if="scope.row.syntaxCheck==='1'">
            <i class="el-icon-success"  style="font-size:15px;color:green"></i>  通过
          </div>
          <div v-else>

            <el-popover
                    placement="top-start"
                    width="300"
                    title="错误语句"
                    trigger="hover"
                    :content="scope.row.syntaxMsg">
              <div slot="reference">

              <i class="el-icon-error"  style="font-size:15px;color:red" ></i>  错误
              </div>
            </el-popover>



          </div>

          <!--<el-tag size="mini"  v-if="scope.row.syntaxCheck==='0'">待检测</el-tag>-->

        </template>
      </el-table-column>
      <el-table-column prop="note" label="备注" width="150" >
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <!--<el-button size="mini" type="text"  style="color: blue" >审核</el-button>-->
          <el-button size="mini" type="text"  @click="recallSqlJob(scope.$index, scope.row)" style="color: gray" v-if="$store.state.user.btnLimit['sqljob-recall']" >撤回</el-button>
          <el-button size="mini" type="text" @click="handleReject(scope.$index, scope.row)" style="color: green" v-if="$store.state.user.btnLimit['sqljob-reject']">拒绝</el-button>
          <el-button type="text" size="mini" @click="handleExec(scope.$index, scope.row)" style="color: red" v-if="$store.state.user.btnLimit['sqljob-exec']" >执行</el-button>
        </template>
      </el-table-column>

    </el-table>
    <el-pagination
            style="float: right;"
            small
            layout="prev, pager, next, sizes, total"
            :pager-count="5"
            :page-sizes="[5, 10, 15, 20,50]"
            :page-size="pagesize"
            :total="sqlJobData.length"
            @current-change="handlePageCurrentChange"
            @size-change="handleSizeChange"
            :hide-on-single-page="true"
    >
    </el-pagination>


    <h4>历史记录</h4>

    <el-collapse v-model="activeNames"   >
      <el-collapse-item title="执行成功" name="1">
        <template slot="title">
            <div style="margin-left: 5px;color: green">执行成功  <i class="header-icon el-icon-success"></i></div>
        </template>
        <div v-for="s in sqlJobSuccess">

          <el-button type="text" style="color: green"  size="small" icon="el-icon-download" @click="downloadSqlJobFile(s.id)">{{s.id}}</el-button>

          {{s.result}}
          <el-button type="text"   size="small" icon="el-icon-more" @click="downloadSqlJobResult(s.id)"></el-button>
        </div>
      </el-collapse-item>

      <el-collapse-item title="执行失败" name="2">
        <template slot="title">
          <div style="margin-left: 5px;color: red">执行失败  <i class="header-icon el-icon-error"></i></div>
        </template>
        <div v-for="s in sqlJobFail">
            &nbsp;<el-button type="text" style="color: red"  size="small" icon="el-icon-download" @click="downloadSqlJobFile(s.id)">{{s.id}}</el-button>
          {{s.result}}
          <el-button type="text"   size="small" icon="el-icon-more" @click="downloadSqlJobResult(s.id)"></el-button>
        </div>

      </el-collapse-item>
    </el-collapse>
  </section>
</template>

<script>
    import { getSqlJobList,rejectDbJob,addSqlJob,getDbList,doSqlJob,sqlJobSyntaxCheck,recallSqlJob } from '../../../api/api'
    import saveAs from 'file-saver';
    var FileSaver = require('file-saver');

  export default {
      data()  {

          var addsqljobchech = (rule, value, callback) => {

              let self = this


                  if (self.addSqlJob.statement.trim() === "") {
                      callback(new Error('请输入SQL'));
                  }else {
                      // callback(new Error('请上传SQL文件sdas'));
                      callback()
                  }




          };
          var uploadSqlCheck = (rule, value, callback) => {

              let self = this

              if (self.sqlfileList.length !== 1) {
                      callback(new Error('请上传SQL文件!'));
                      // callback()
              } else {
                  callback()
              }




          };

          return {
              filters: {
                  sqlid: ''
              },


              sqlJobData: [
              ],
              activeNames: ['3'],
              sqlJobSuccess: [

              ],
              sqlJobFail: [
              ],
              dialogFormVisible: false,

              addSqlJob: {
                  dbChoice: [],
                  type: 1, //0 DDL , 1 DML
                  dbname: "",
                  statement: "",
                  comment:"",
              },
              sqlfileList: [],   //上传的文件
              contentType: 0,  //0 在线编辑 ： 1 文件上传

              formLabelWidth: '100px',

              addsqlJobRules: {

                  SqlEdit: [
                      { required: true, validator: addsqljobchech, trigger: 'blur' },
                  ],
                  uploadSql: [
                      { required: true, validator: uploadSqlCheck, trigger: 'blur' },
                  ],


              },

              //分页
              pagesize: 10,
              currpage: 1,
          }
      },
      methods: {



          //拒绝执行sql
          handleReject: function (index, row) {
              this.$prompt('请输入拒绝原因', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
              }).then(({ value }) => {
                  //api to /api/server/updateSqlJobList
                  var updateParams = {id:row.id,status:2,result:value}
                  rejectDbJob(updateParams)

                  this.sqlJobData.splice(index,1)
                  this.sqlJobFail.unshift({id:row.id,result:value})
              }).catch(() => {

              });
          },
          trim(s){
              return s.replace(/(^\s*)|(\s*$)/g, "");
    },
          //执行sql
          handleExec: function (index, row) {
              this.$confirm('确认执行该SQL吗?', '提示', {
                  type: 'warning '
              }).then(() => {
                  console.log("here...",this.trim(row.statement).substring(0,6).toLowerCase())

                  // if (this.trim(row.statement).substring(0,6).toLowerCase() === "select" ) {
                  //     //拒绝查询语句
                  //
                  //     var updateParams = {id:row.id,status:2,result:"拒绝执行查询语句", statement:row.statement}
                  //     updateSqlJob(updateParams)
                  //
                  //     this.sqlJobData.splice(index,1)
                  //     this.sqlJobFail.unshift({id:row.id,result:"拒绝执行查询语句", statement:row.statement})
                  //     return
                  // }



                  var para = { id: row.id };
                  doSqlJob(para).then((res) => {
                      console.log(res.code)
                      if (res.code === 200) {
                          this.sqlJobData.splice(index,1)
                          this.sqlJobSuccess.unshift({id:row.id , result: res.message , statement:row.statement})
                      } else if (res.code === 400) {

                          this.sqlJobData.splice(index,1)
                          this.sqlJobFail.unshift({id:row.id , result:res.error , statement:row.statement})
                      }


                  })
                  //this.sqlJobData.splice(index,1)
                  //this.sqlJobSuccess.unshift({id:row.id,result:"后台任务返回数据暂未处理"})



              }).catch(() => {

              });
          },
          sqlSyntaxCheck:function(index,row){
              var para = { id: row.id };
              sqlJobSyntaxCheck(para).then((res) => {

              })
          },
          recallSqlJob:function(index,row){

              this.$confirm('确定撤回任务？', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
              }).then(({ value }) => {
                  //api to /api/server/updateSqlJobList
                  var para = { id: row.id };
                  recallSqlJob(para).then((res) => {
                      console.log("recall .......")
                      console.log(res)
                          if (res.code === 200){
                          console.log("success")
                              this.$message({
                                  message: "已撤回!",
                                  type: 'success'
                              });
                          }else {
                              console.log("error")
                              this.$message({
                                  message: res.message,
                                  type: 'error'
                              });
                          }

                  })

                  this.sqlJobData.splice(index,1)

              }).catch(() => {

              });





          },
          getSqlJobListData(){
              var params = {dbname : this.$route.params.name,token:this.$store.state.user.token}
              //console.log("debug get param" , params)
              getSqlJobList(params).then((res) => {
                      //console.log(res.data.list)
                      //this.userList = res.data.users
                      if (res.data.jobs.undeal === null) {
                          this.sqlJobData = []
                      }else {
                          this.sqlJobData = res.data.jobs.undeal
                      }


                      this.sqlJobSuccess = res.data.jobs.success
                      this.sqlJobFail = res.data.jobs.failed

                  }
              )
          },
          // addSqlJobConfirm(formName) {
          //
          //
          //     this.$refs[formName].validate((valid) => {
          //         if (valid) {
          //             var param = {dbname:this.addSqlJob.dbname,statement:this.addSqlJob.statement}
          //             if (this.$route.params.name === this.addSqlJob.dbname) {
          //                 this.$router.go(0);
          //             }else {
          //                 console.log("debug not ")
          //             }
          //             addSqlJob(param)
          //
          //             console.log(this.contentType)
          //             console.log(this.sqlfileList)
          //
          //             // this.dialogFormVisible = false
          //
          //
          //         } else {
          //             console.log('error submit!!');
          //             return false;
          //         }
          //     });
          //
          //
          //
          //
          //
          //
          // },
          addSqlJobConfirm(formName) {


              this.$refs[formName].validate((valid) => {
                  if (valid) {


                      console.log(this.$route.params.name)

                      let wfForm = new FormData();
                      wfForm.append( 'dbname', this.$route.params.name,)
                      wfForm.append( 'statement', this.addSqlJob.statement,)
                      wfForm.append( 'comment', this.addSqlJob.comment,)
                      wfForm.append( 'submitter', this.$store.state.user.name,)
                      wfForm.append( 'department', this.$store.state.user.department,)
                      if (this.addSqlJob.type === 0) {
                          wfForm.append( 'type', "ddl",)
                      } else {
                          wfForm.append( 'type', "dml",)
                      }
                      if (this.contentType === 0) {
                          wfForm.append( 'method', "edit",)
                      } else {
                          wfForm.append( 'method', "upload",)
                      }

                      console.log(wfForm.get('method'))


                      if (this.sqlfileList.length > 0 && this.contentType === 1) {
                          console.log("debug herer")
                          console.log(this.sqlfileList.length)
                          console.log(this.contentType)

                          Object.entries(this.sqlfileList).forEach(file => {
                              // file[1].forEach(item => {
                              //     wfForm.append('files', item.raw)
                              //     wfForm.append(item.name, file[0])
                              // })
                              wfForm.append('filename', file[1].name)
                              wfForm.append('file', file[1].raw)
                              // console.log()
                              // console.log(file[1].raw)
                          })
                      }


                      addSqlJob(wfForm).then((res) => {
                          console.log("debug here")
                          console.log(res.code)
                          if (res.code === 400) {
                              console.log("why not")
                              this.$message({
                                  message: res.message,
                                  type: 'error'
                              });
                          }else {
                              this.dialogFormVisible = false
                          }
                          // this.dialogFormVisible = false
                      })


                  } else {
                      console.log('error submit!!');
                      return false;
                  }
              });






          },
          chooseDbs(){
              getDbList().then((res) => {
                      console.log(res.data.dblist)
                  this.addSqlJob.dbChoice = res.data.dblist
                      //this.userList = res.data.users
                      //this.dbs = res.data.dblist
                  }
              )
          },
          openDialog() {
              this.addSqlJob.dbname = ""
              this.addSqlJob.statement = ""
          },

          getSqlJobById() {
              let self = this
              if (self.filters.sqlid.trim() === ""){
                  return
              }
              self.sqlJobData  = self.sqlJobData.filter( function (value) {
                      return value.id === self.filters.sqlid
                  }
              )
          },

          beforeAvatarUpload(file) {
              const isLt500K = file.size / 1024 / 1024 < 2;
              if (!isLt500K) {
                  this.$message.error('上传文件大小不能超过 2M!');
              }
              return isLt500K
          },
          handleAvatarSuccess(res, file) {
              //console.log(res.filename)
              //console.log(file)
              this.$message({
                  message: " 上传成功" ,
                  type: 'success'
              });
          },
          handleAvatarError(res) {
              this.$message({
                  message: "上传失败" + res.message ,
                  type: 'success'
              });

          },
          handleExceed(files, fileList) {
              // console.log(fileList)
              this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
          },
          fileChange(file,fileList) {
              console.log(file, fileList);
              this.sqlfileList = fileList;

              // this.files[''] = fileList;
          },

          //分页
          handlePageCurrentChange(cpage) {
              this.currpage = cpage;
          },
          handleSizeChange(psize) {
              this.pagesize = psize;
          },
          downloadSqlJobFile(id){
              //alert("this: " + db + "   " +  sql)
              let filename = id + ".sql"
              let url = "http://127.0.0.1:8088/" + "static/ddl-dml/" + filename
              FileSaver.saveAs(url,filename)
          },
          downloadSqlJobResult(id){
              //alert("this: " + db + "   " +  sql)
              let filename = id + "-result.txt"
              let url = "http://127.0.0.1:8088/" + "static/ddl-dml/" + filename
              FileSaver.saveAs(url,filename)
          },
      },
      mounted() {
          // console.log("debug here" , this.$route.params.name)
          // let user = this.$store.state.user;
          // console.log(user.name)
          // console.log(user.department)

          console.log("debug btn permisson here ....")
          console.log(this.$store.state.user.btnLimit['sqljob-exec'])

          this.getSqlJobListData();
      },
  }
</script>

<style>
  #mysql-manager-job .toolbar {
    height: 50px;
  }

  #mysql-manager-job .minibutton{
    -webkit-transform: scale(0.6) !important;
  }

  #mysql-manager-job .el-collapse-item__header{
    background-color: #B0C4DE;
    height: 30px;
    border-radius: 8px;
    margin-bottom: 3px;

  }
  #mysql-manager-job .el-collapse-item__content {
    padding-bottom: 5px;

  }
  #mysql-manager-job .bg-red .is-checked .el-radio__inner {
    border-color: red;
    background-color: red;

  }
  #mysql-manager-job .el-dialog__body {
    padding: 10px 10px;
  }
  #mysql-manager-job .el-form-item {
    margin-bottom: 10px;

  }




</style>